<template>
  <div class="uploader-file">
    <label class="label-box">
      <input type="file" @change="upload" />
      <i class="el-icon-plus"></i>
      <img class="auto-img pro-img" :src="src" alt="" v-if="src"/>
    </label>
  </div>
</template>

<script>
  import '../assets/less/b_uploader-file.less'
  export default {
    name: 'UploaderFile',
    props: {
      size: {
        type: [Number, String],
        //单位：KB
        default: 10240
      },
      type: {
        type: Array,
        default() {
          return ['jpg', 'jpeg', 'png', 'gif'];
        }
      }
    },
    data() {
      return {
        src: ''
      };
    },
    methods: {
      upload(e) {
        let self = this;

        let file = e.target.files[0];
        console.log('file ==> ', file);

        //判断文件是否为图片类型
        let type = file.type.split('/')[1];
        if (this.type.indexOf(type) === -1) {
          e.target.value = '';
          return this.$message.error(`文件格式只支持${this.type.join(',')}`); 
        }

        //判断图片大小是否合法
        if (file.size / 1024 > this.size) {
          e.target.value = '';
          return this.$message.error(`文件大小不能超过${this.size/1024}MB`);
        }


        let fileReader = new FileReader();

        fileReader.onload = function () {
          // console.log('this.result ==> ', this.result);
          self.src = this.result;

          //触发一个自定义事件，并且携带base64传递给父组件
          self.$emit('upload', {base64: this.result, type});
        }

        if (file) {
          fileReader.readAsDataURL(file);
        }
      }
    }
  }
</script>